package p34_HandlerMapper和HandlerAdapter其2;

import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.function.*;
import org.springframework.web.servlet.function.support.HandlerFunctionAdapter;
import org.springframework.web.servlet.function.support.RouterFunctionMapping;

/**
 * 这章介绍下HandlerMapping和HandlerAdapter接口的另一组实现,RouterFunctionMapping和HandlerFunctionAdapter
 * 1.RouterFunctionMapping：收集所有RouterFunction，作为控制器
 * 2.HandlerFunctionAdapter：根据请求uri从RouterFunctionMapping找到控制器(handler)，然后由HandlerFunctionAdapter调用控制器handler
 */
@Configuration
public class _1_RouterFunctionMapping和HandlerFunctionAdapter {
    public static void main(String[] args) {
        /**
         * 函数式控制器
         *    1.RouterFunctionMapping，通过RequestPredicate来映射路径
         *    2.handler 实现HandlerFunction接口
         *    3.HandlerFunctionAdapter，调用handler
         * 将来请求进来，就会将请求与RouterFunctions的RequestPredicates作对比，匹配成功就会调用该RouterFunctions的handler方法
         *
         * 对比传统的
         *    1.RequestMappingInfoHandlerMapping，以@RequestMapping作为映射路径
         *    2.控制器的具体方法会被当做handler
         *    3.RequestMappingHandlerAdapter，调用handler
         */
        AnnotationConfigServletWebServerApplicationContext context =
                new AnnotationConfigServletWebServerApplicationContext(FunctionWebConfig.class);
    }
    //注入RouterFunctionMapping
    @Bean
    public RouterFunctionMapping routerFunctionMapping() {
        return new RouterFunctionMapping();
    }
    //注入HandlerFunctionAdapter
    @Bean
    public HandlerFunctionAdapter handlerFunctionAdapter() {
        return new HandlerFunctionAdapter();
    }

    /**
     * 注入RouterFunction，RouterFunctionMapping初始化时会收集RouterFunction类型的bean
     * @return
     */
    @Bean
    public RouterFunction<ServerResponse> r1() {
        return RouterFunctions.route(RequestPredicates.GET("/r1"), request -> ServerResponse.ok().body("this is r1"));
    }

    @Bean
    public RouterFunction<ServerResponse> r2() {
        return RouterFunctions.route(RequestPredicates.GET("/r2"), request -> ServerResponse.ok().body("this is r2"));
    }
}
